/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 jfinal app. jfapp Group.
 */

package app.models.member;

import app.Const;
import app.kit.TypeKit;
import com.google.common.base.Optional;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import goja.annotation.TableBind;
import goja.lang.Lang;
import goja.plugins.sqlinxml.SqlKit;

import java.math.BigDecimal;
import java.util.List;

import static app.Const.FIELD_INTEGRAL;

/**
 * <p>
 *  积分规则表
 * </p>
 */
@TableBind(tableName = "rls_points")
public class Points extends Model<Points> {

    /**
     * The public dao.
     */
    public static final Points dao = new Points();

    private static final long serialVersionUID = 8864661739173348753L;

    /**
     * 查询所有可用的
     * @return 可用列表
     */
    public List<Points> findAvailableAll() {
        return find(SqlKit.sql("points.findAvailableAll"));
    }

    public Optional<Points> findByCode(String code) {
        Points pointses = findFirst(SqlKit.sql("points.findByCode"), code,1);
        if (Lang.isEmpty(pointses)) {
            return Optional.absent();
        }
        return Optional.of(pointses);
    }

    public boolean setEnableByCode(String code) {
        return Db.update(SqlKit.sql("points.setEnableByCode"),code) > 0;
    }

    public boolean setDisableByCode(String code) {
        return Db.update(SqlKit.sql("points.setDisableByCode"),code) > 0;
    }


    /**
     * 消费产品得到积分
     *
     * @param amount 消费金额
     * @return 赠送积分
     */
    public int consumption(BigDecimal amount) {
        Optional<Points> optional_points = Points.dao.findByCode(Const.POINTS_CODE.COST);
        if (optional_points.isPresent()) {
            final Points points = optional_points.get();
            if (TypeKit.getStatus(points) == 1) {
                int integral = TypeKit.getInt(points, FIELD_INTEGRAL);
                int ratio_val = TypeKit.getInt(points, "ratio_val");
                if(ratio_val <= 0){
                    return 0;
                }
                return amount.divide(new BigDecimal(ratio_val), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(integral)).intValue();

            }
        }
        return 0;
    }

    public Points invite() {
        Optional<Points> invite = Points.dao.findByCode(Const.POINTS_CODE.INVITE);
        if (invite.isPresent()) {
            return invite.get();
        } else {
            return null;
        }
    }
}